// 给定一个正整数n，生成一个包含1到n平方的所有元素，且按照顺时针螺旋排列的n * n的正方形矩阵matrix

// 思路，和上题一致，边界指针控制好，初始化一个matric，把结果存入
// 时间复杂度：O(n^2)
// 空间复杂度：O(n^2)

function generateMatrix(n) {
    let top = 0
    let bottom = n - 1
    let left = 0
    let right = n - 1
    let matrix = new Array(n).fill(0).map(item => new Array(n).fill(0))
    let index = 1
    while (true) {
        for (let i = left; i <= right; i++) {
            matrix[top][i] = index
            index++
        }
        top++
        if (top > bottom) {
            break
        }
        for (let i = top; i <= bottom; i++) {
            matrix[i][right] = index
            index++           
        }
        right--
        if (right < left) {
            break
        }
        for (let i = right; i >= left; i--) {
            matrix[bottom][i] = index
            index++
        }
        bottom--
        if (bottom < top) {
            break
        }
        for (let i = bottom; i >= top; i--) {
            matrix[i][left] = index
            index++           
        }
        left++
        if (left > right) {
            break
        }
    }
    return matrix
}

console.log(generateMatrix(3));

// 思路2，同样是控制边界，startRow表示从哪一行开始遍历，startCol从哪一列开始遍历，offset每遍历一轮加1
function generateMatrix2(n) {
    let startRow = 0
    let startCol = 0
    let offset = 1
    let count = 1
    let mid = Math.floor(n / 2)
    let loop = mid
    let ans = new Array(n).fill(0).map((_) => new Array(n).fill(0))
    while (loop--) {
        let row = startRow
        let col = startCol
        while (col < n - offset) {
            ans[row][col] = count++
            col++
        }
        while (row < n - offset) {
            ans[row][col] = count++
            row++
        }
        // 这里注意不能等于
        while (col > startCol) {
            ans[row][col] = count++
            col--
        }
        while (row > startRow) {
            ans[row][col] = count++
            row--
        }
        startCol++
        startRow++
        offset++
    }
    if (n % 2 !== 0) {
        ans[mid][mid] = count
    }
    return ans
}

console.log(generateMatrix2(3));